package com.avic.rong.activity.no;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.avic.rong.R;
import com.avic.rong.fragment.FragmentCart;
import com.avic.rong.fragment.FragmentShop;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchIndexActivity extends AppCompatActivity {


    public static String ARG_URL = "arg_url";
    public static String ARG_FROM  = "from";

    @BindView(R.id.webview)
    BridgeWebView webView;


    private String comeFrom;
    String url = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_index);
        if (getIntent() != null){
            comeFrom = getIntent().getStringExtra(ARG_FROM);
            url = getIntent().getStringExtra(ARG_URL);
        }
        ButterKnife.bind(this);

        webView.loadUrl(url);

        webView.registerHandler("pushVc", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                data = data.replace("\\","");
                JsonObject jsonObject = (JsonObject)new JsonParser().parse(data);
                String currentUrl = jsonObject.get("url").getAsString();

                if (!TextUtils.isEmpty(comeFrom)){
                    if (comeFrom.equals(FragmentShop.ARG_COME_HOME) || comeFrom.equals(FragmentCart.ARG_FROM_CAT) || comeFrom.equals(UserMoneyListActivity.ARG_FROM_MONEY_LIST)){
                        startActivity(CriterionListActivity.queryIntent(SearchIndexActivity.this,currentUrl));
                    }
                }else{
                    Intent dataIntent = new Intent();
                    dataIntent.putExtra("url",currentUrl);
                    setResult(100,dataIntent);
                    finish();
                }
            }
        });

        //app/searchIndex页面的返回
        webView.registerHandler("goBack", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
            }
        });
    }


    public static Intent queryIntent(Context context,String url){
        Intent intent = new Intent(context,SearchIndexActivity.class);
        intent.putExtra(ARG_URL,url);
        return intent;
    }

    public static Intent queryIntent(Context context,String url,String fromSource){
        Intent intent = new Intent(context,SearchIndexActivity.class);
        intent.putExtra(ARG_URL,url);
        intent.putExtra(ARG_FROM,fromSource);
        return intent;
    }


}
